package com.powerwyx.project.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powerwyx.apiclientsdk.client.ApiClient;
import com.powerwyx.apicommon.model.entity.InterfaceInfo;
import com.powerwyx.apicommon.model.entity.User;
import com.powerwyx.project.common.ErrorCode;
import com.powerwyx.project.common.IdRequest;
import com.powerwyx.project.exception.BusinessException;
import com.powerwyx.project.mapper.InterfaceInfoMapper;
import com.powerwyx.project.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.powerwyx.project.model.enums.InterfaceInfoStatusEnum;
import com.powerwyx.project.service.InterfaceInfoService;
import com.powerwyx.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author 17585
* @description 针对表【interface_info】的数据库操作Service实现
* @createDate 2024-07-29 21:18:56
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService {

    @Autowired
    private ApiClient apiClient;

    @Autowired
    private UserService userService;

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = interfaceInfo.getId();
        String name = interfaceInfo.getName();
        String description = interfaceInfo.getDescription();
        String url = interfaceInfo.getUrl();
        String requestHeader = interfaceInfo.getRequestHeader();
        String responseHeader = interfaceInfo.getResponseHeader();
        Long userId = interfaceInfo.getUserId();
        String method = interfaceInfo.getMethod();
        Integer status = interfaceInfo.getStatus();
        Date createTime = interfaceInfo.getCreateTime();
        Date updateTime = interfaceInfo.getUpdateTime();
        Integer isDelete = interfaceInfo.getIsDelete();
        // 创建时，所有参数必须非空
        if (add) {
            if (StrUtil.isBlank(name)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
        }
        if (StrUtil.isNotBlank(name) && name.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }
    }


    /**
     *发布接口
     */
    @Override
    public void onlineInterfaceInfo(IdRequest idRequest) {
        if(idRequest == null || idRequest.getId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询当前接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(idRequest.getId());
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断接口是否可以调用
        com.powerwyx.apiclientsdk.model.User user = new com.powerwyx.apiclientsdk.model.User();
        user.setUsername("test");
        String name = apiClient.getNameByPost(user);
        if(StrUtil.isBlank(name)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"接口验证失败");
        }

        //上线接口
        InterfaceInfo interfaceInfo = InterfaceInfo.builder()
                .id(idRequest.getId())
                .status(InterfaceInfoStatusEnum.ONLINE.getValue())
                .build();
        boolean isSuccess = updateById(interfaceInfo);
        if(!isSuccess){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }


    /**
     * 下线接口
     * @param idRequest
     */
    @Override
    public void offlineInterfaceInfo(IdRequest idRequest) {
        if(idRequest == null || idRequest.getId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询当前接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(idRequest.getId());
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        //上线接口
        InterfaceInfo interfaceInfo = InterfaceInfo.builder()
                .id(idRequest.getId())
                .status(InterfaceInfoStatusEnum.OFFLINE.getValue())
                .build();
        boolean isSuccess = updateById(interfaceInfo);
        if(!isSuccess){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

    }


    /**
     * 测试调用接口
     * @param interfaceInfoInvokeRequest
     */
    @Override
    public String InterfaceInfoInvoke(InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        if(interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = interfaceInfoInvokeRequest.getId();
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        //查询接口是否存在
        InterfaceInfo interfaceInfo = getById(id);
        if(interfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if(interfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");
        }
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        ApiClient apiClient = new ApiClient(accessKey, secretKey);
        com.powerwyx.apiclientsdk.model.User user = JSONUtil.toBean(userRequestParams, com.powerwyx.apiclientsdk.model.User.class);
        return apiClient.getNameByPost(user);
    }


}




